package com.atguigu.daijia.order.handle;

import cn.hutool.core.util.StrUtil;
import com.atguigu.daijia.order.service.OrderInfoService;
import com.atguigu.daijia.order.service.impl.OrderInfoServiceImpl;
import jakarta.annotation.PostConstruct;
import org.checkerframework.checker.units.qual.A;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//监听延迟队列,拿到消息后取消订单
@Component
public class RedisDelayHandle {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private OrderInfoServiceImpl orderInfoService;

    //在bean创建完后执行
    @PostConstruct
    public void lisener(){
        //实现对延迟队列的监听
        new Thread(()->{
            while (true){
                //获取延迟队列中的阻塞队列
                RBlockingQueue<String> blockingQueue = redissonClient.getBlockingQueue("queue_cancel");
                //从队列中获取消息
                try {
                    String orderId = blockingQueue.take();
                    //取消订单
                    if(StrUtil.isNotBlank(orderId)){
                        orderInfoService.orderCancel(Long.parseLong(orderId));
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();

    }
}
